import Api, { Response } from "@/src/lib/api/api"
import Global from "@/src/lib/global"
import GoodsCartListModel from "@/src/lib/models/goods_cart_list_model"
import GoodsCartModel from "@/src/lib/models/goods_cart_model"


export interface CartState {
    goodsprice: any

    goodsList: GoodsCartModel[],
    invalidGoodsList: GoodsCartModel[],
    totalGoodsNum: number
}

export default {
    namespace: "cart",
    state: {
        totalGoodsNum: 0,
        goodsList: [],
        invalidGoodsList: []
    },
    reducers: {
        setState(state, { payload }) {
            return { ...state, ...payload }
        },

        setTotalGoodsNum(state, { payload }) {
            return { ...state, ...{ totalGoodsNum: payload }}
        }
    },
    effects: {
        *add({ payload }, { put, call }) {

            let res: Response = yield call(Api.goodsCartAdd, payload)
            if (!Api.handleResponse(res)) {
                return
            }

            Global.showToast("添加成功\r\n在购物车等你哟~")
            yield put({
                type: "getCartList"
            })

            yield put({
                type: "temp/shopcartInsertSelectedGoodsId",
                payload: payload.goodsid
            })
            
            return true
        },

        *orderAdd({ payload }, { put, call }) {
            let res: Response = yield call(Api.goodsOrderAddToCart, {
                orderid: payload.orderid,
                goodsid: payload.goodsid
            })

            if (!Api.handleResponse(res)) {
                return
            }
            Global.showToast("添加成功\r\n在购物车等你哟~")
            yield put({
                type: "getCartList"
            })

            yield put({
                type: "temp/shopcartInsertSelectedGoodsId",
                payload: payload.realGoodsId
            })

            return true
        },

        *orderAddAll({ payload }, { put, call }) {
            let res: Response = yield call(Api.goodsOrderAddAllToCart, {
                orderid: payload,
            })

            if (!Api.handleResponse(res)) {
                return
            }

            Global.showToast("添加成功\r\n在购物车等你哟~")

            yield put({
                type: "getCartList"
            })

            return true
        },

        *getCartList({}, { put, call }) {
            let res: Response = yield call(Api.goodsCartList)
            if (!Api.handleResponse(res)) {
                return
            }
            console.log('res.data',res.data)
            let model: GoodsCartListModel|any = res.data
            let totalGoodsNum = 0
           
            for (const goods of model.goodslist1) {
                goods.loc_isSelling = true
                totalGoodsNum += Number.parseInt(goods.num)
                // goods.freetitle=freetitle?freetitle:''
            }

            let goodsList = model.goodslist1
            let invalidGoodsList = model.goodslist2
          

            yield put({
                type: "temp/shopcartRemoveSelectedGoodsId",
                payload: invalidGoodsList.map((model) => model.goodsid)
            })

            yield put({
                type: "setState",
                payload: {
                    goodsList: goodsList,
                    invalidGoodsList: invalidGoodsList,
                    couponTip: model.coupontip,
                    orderPrice: model.orderprice,
                    totalGoodsNum: totalGoodsNum,
                   
                }
            })
        },
        
        /**
         * payload: {
         *  goodsid: string,
         *  addnum: "1" | "-1"
         * }
         */
        *adjustNum({ payload }, { put, call, select }){
            let goodsid = payload.goodsid as string
            let addnum = payload.addnum as string
            // let goodsprice = payload.
            let res: Response = yield call(Api.goodsCartNum, payload)
            console.log('res 添加',res)
            if (!Api.handleResponse(res)) {
                return
            }

            let cart: CartState = yield select(state => state.cart)
            let goodsList = cart.goodsList
            let totalGoodsNum = cart.totalGoodsNum;
            // let goodsprice = cart.goodsprice;
            for (let model of goodsList) {
                if (model.goodsid == goodsid) {
                    let num = Number.parseInt(model.num)
                    if (addnum == "1") {
                        num += 1
                        totalGoodsNum += 1

                    } else {
                        num -= 1
                        totalGoodsNum -= 1
                    }
                    model.goodsprice =res.data.goodsprice
                    model.freetitle = res.data.freetitle
                    model.num = num.toString();
                    console.log('modelcratad',model)
                    break
                }
            }
          

            yield put({
                type: "setState",
                payload: {
                    goodsList: JSON.parse(JSON.stringify(goodsList)),
                    totalGoodsNum: totalGoodsNum
                }
            })   
        },

        /**
         * 清理无效的商品
         */
        *clearInvalidGoods({}, { put, call}) {
            let res: Response = yield call(Api.goodsCartClearNoSellGoods)
            if (!Api.handleResponse(res)) {
                return
            }

            yield put({
                type: "setState",
                payload: {
                    invalidGoodsList: [],
                }
            })  
        },

        /**
         * 删除商品
         * payload: string[]
         */
        *removeGoods({ payload }, { put, call, select }) {
            let set = new Set<string>(payload)

            let res: Response = yield call(Api.goodsCartDel, { idlist: payload})
            if (!Api.handleResponse(res)) {
                return false
            }
            
            let cart: CartState  = yield select(state => state.cart)
            let totalGoodsNum = cart.totalGoodsNum
            let goodsList = cart.goodsList.filter((model) => {
                totalGoodsNum -= Number.parseInt(model.num)
                return !set.has(model.goodsid)
            })

            yield put({
                type: "temp/shopcartRemoveSelectedGoodsId",
                payload: Array.from(set)
            })

            yield put({
                type: "setState",
                payload: {
                    goodsList: goodsList,
                    totalGoodsNum: totalGoodsNum
                }
            })
            
            return true
        },

        *removeGoodsLocal({ payload }, { put, select }) {
            let set = new Set<string>(payload)

            let cart: CartState  = yield select(state => state.cart)
            let totalGoodsNum = cart.totalGoodsNum
            let goodsList = cart.goodsList.filter((model) => {
                totalGoodsNum -= Number.parseInt(model.num)
                return !set.has(model.goodsid)
            })

            yield put({
                type: "temp/shopcartRemoveSelectedGoodsId",
                payload: Array.from(set)
            })

            yield put({
                type: "setState",
                payload: {
                    goodsList: goodsList,
                    totalGoodsNum: totalGoodsNum
                }
            })
            
            return true
        },
    }
}